/**
 * 现代化API架构使用示例
 * 展示如何使用新的ApiFactory、依赖注入和统一错误处理
 */

import { ApiCall } from 'tsrpc';
import { ApiFactory, Api, PlayerApi, CachedApi } from '../infrastructure/api/ApiFactory';
import { ApiHelper, ApiErrorCode } from '../infrastructure/api/ApiHelper';
import { createApiContext, ServiceIdentifiers } from '../infrastructure/di/ServiceContainer';

// ==================== 方式1: 使用ApiFactory ====================

/**
 * 示例1: 简单的API处理器
 * 使用ApiFactory.createSimpleHandler快速创建API
 */
export const GetServerInfo = ApiFactory.createSimpleHandler(
    async (req: any, context) => {
        const commonTools = context.commonTools;
        
        return {
            serverName: '示例服务器',
            version: '1.0.0',
            timestamp: commonTools.getTimestamp(),
            players: context.userManager.getOnlinePlayerCount()
        };
    },
    {
        name: 'GetServerInfo',
        enableMonitoring: true
    }
);

/**
 * 示例2: 玩家相关API
 * 使用ApiFactory.createPlayerHandler自动处理玩家验证
 */
export const GetPlayerInfo = ApiFactory.createPlayerHandler(
    async (req: { playerId: string }, player, context) => {
        const rpgService = context.rpgService;
        const bagService = context.bagService;
        
        // 获取玩家数据
        const rpgData = await rpgService.getPlayerRPGData(req.playerId);
        const bagData = await bagService.getPlayerBag(req.playerId);
        
        return {
            playerId: req.playerId,
            level: rpgData.level,
            experience: rpgData.experience,
            bagItems: bagData.items.length,
            lastLogin: player.lastLoginTime
        };
    },
    {
        name: 'GetPlayerInfo',
        requiredParams: ['playerId']
    }
);

/**
 * 示例3: 带缓存的API
 * 使用ApiFactory.createCachedHandler实现结果缓存
 */
export const GetPlayerStats = ApiFactory.createCachedHandler(
    async (call: ApiCall<{playerId: string}, any>, context) => {
        const playerId = call.req.playerId;
        const rpgService = context.rpgService;
        
        // 获取玩家统计数据（计算密集型操作）
        const stats = await rpgService.calculateDetailedStats(playerId);
        
        ApiHelper.success(call, stats);
    },
    (req) => `player_stats:${req.playerId}`, // 缓存key生成器
    10 * 60 * 1000, // 10分钟缓存
    {
        name: 'GetPlayerStats',
        requirePlayer: true
    }
);

// ==================== 方式2: 使用装饰器 ====================

/**
 * API服务类示例
 * 使用装饰器定义API处理器
 */
export class PlayerApiService {
    /**
     * 基础API装饰器使用
     */
    @Api({
        name: 'UpdatePlayerProfile',
        requiredParams: ['playerId', 'profileData'],
        requirePlayer: true
    })
    async updateProfile(call: ApiCall<any, any>, context: any) {
        const { playerId, profileData } = call.req;
        
        // 使用依赖注入获取服务
        const userService = await context.getService(ServiceIdentifiers.USER_MANAGER);
        
        // 更新玩家资料
        await userService.updatePlayerProfile(playerId, profileData);
        
        ApiHelper.success(call, { message: '资料更新成功' });
    }
    
    /**
     * 玩家API装饰器使用
     */
    @PlayerApi({
        name: 'GetPlayerBag',
        requiredParams: ['playerId']
    })
    async getPlayerBag(req: { playerId: string }, player: any, context: any) {
        const bagService = context.bagService;
        const bagData = await bagService.getPlayerBag(req.playerId);
        
        return {
            playerId: req.playerId,
            items: bagData.items,
            capacity: bagData.maxSize,
            freeSlots: bagData.maxSize - bagData.items.length
        };
    }
    
    /**
     * 缓存API装饰器使用
     */
    @CachedApi(
        (req) => `leaderboard:${req.type}:${req.page}`,
        5 * 60 * 1000, // 5分钟缓存
        {
            name: 'GetLeaderboard',
            requiredParams: ['type', 'page']
        }
    )
    async getLeaderboard(call: ApiCall<any, any>, context: any) {
        const { type, page } = call.req;
        const rpgService = context.rpgService;
        
        const leaderboard = await rpgService.getLeaderboard(type, page, 10);
        ApiHelper.success(call, leaderboard);
    }
}

// ==================== 方式3: 手动使用ApiHelper ====================

/**
 * 示例4: 手动使用ApiHelper和依赖注入
 * 适合需要完全控制的复杂API
 */
export async function ComplexBattleApi(call: ApiCall<any, any>) {
    ApiHelper.logApiCall(call, 'ComplexBattleApi');
    
    try {
        // 参数验证
        const validation = ApiHelper.validateRequired(call.req, ['playerId', 'targetId', 'battleType']);
        if (!validation.isValid) {
            ApiHelper.missingParams(call, validation.missing);
            return;
        }
        
        // 获取服务上下文
        const context = createApiContext();
        
        // 验证玩家
        const { playerId, targetId, battleType } = call.req;
        const player = context.userManager.getOnlinePlayer(playerId);
        if (!ApiHelper.checkPlayerOnline(player, call, playerId)) {
            return;
        }
        
        const target = context.userManager.getOnlinePlayer(targetId);
        if (!ApiHelper.checkPlayerExists(target, call, targetId)) {
            return;
        }
        
        // 验证战斗类型
        const validBattleTypes = ['pvp', 'pve', 'boss'];
        if (!validBattleTypes.includes(battleType)) {
            ApiHelper.invalidParams(call, `无效的战斗类型: ${battleType}`);
            return;
        }
        
        // 业务逻辑
        const rpgService = context.rpgService;
        const battleResult = await rpgService.startBattle(player, target, battleType);
        
        // 成功响应
        ApiHelper.success(call, {
            battleId: battleResult.battleId,
            status: 'started',
            estimatedDuration: battleResult.estimatedDuration
        });
        
    } catch (error) {
        if (error instanceof Error) {
            if (error.message.includes('冷却')) {
                ApiHelper.error(call, 'BATTLE_COOLDOWN', error.message);
            } else if (error.message.includes('资源不足')) {
                ApiHelper.error(call, ApiErrorCode.INSUFFICIENT_RESOURCES, error.message);
            } else {
                ApiHelper.internalError(call, error.message, error);
            }
        } else {
            ApiHelper.internalError(call, '战斗启动失败');
        }
    }
}

// ==================== 批量操作示例 ====================

/**
 * 示例5: 批量操作API
 * 展示如何处理批量请求和优化查询
 */
export const BatchGetPlayerData = ApiFactory.createHandler(
    async (call: ApiCall<{playerIds: string[]}, any>, context) => {
        const { playerIds } = call.req;
        
        // 验证批量大小
        if (playerIds.length > 100) {
            throw new Error('批量查询数量不能超过100');
        }
        
        // 使用优化的Repository进行批量查询
        const bagRepository = await context.getService(ServiceIdentifiers.BAG_REPOSITORY);
        const rpgRepository = await context.getService(ServiceIdentifiers.RPG_REPOSITORY);
        
        // 并行获取数据
        const [bagDataMap, rpgDataMap] = await Promise.all([
            bagRepository.getPlayerBags(playerIds),
            rpgRepository.getPlayerRPGDataBatch(playerIds)
        ]);
        
        // 组装结果
        const results = playerIds.map(playerId => ({
            playerId,
            bagData: bagDataMap.get(playerId) || null,
            rpgData: rpgDataMap.get(playerId) || null
        }));
        
        ApiHelper.success(call, {
            players: results,
            total: results.length,
            cached: results.filter(r => r.bagData && r.rpgData).length
        });
    },
    {
        name: 'BatchGetPlayerData',
        requiredParams: ['playerIds'],
        timeout: 30000 // 30秒超时
    }
);

// ==================== 错误处理示例 ====================

/**
 * 示例6: 错误处理演示
 * 展示各种错误场景的处理方法
 */
export const ErrorHandlingDemo = ApiFactory.createHandler(
    async (call: ApiCall<{action: string}, any>, context) => {
        const { action } = call.req;
        
        switch (action) {
            case 'missing_params':
                // 演示参数缺失错误
                throw new Error('缺少必需参数: userId');
                
            case 'player_not_found':
                // 演示玩家不存在错误
                throw new Error('玩家不存在');
                
            case 'insufficient_resources':
                // 演示资源不足错误
                throw new Error('金币不足，无法完成操作');
                
            case 'permission_denied':
                // 演示权限错误
                throw new Error('权限不足，无法访问该功能');
                
            case 'system_error':
                // 演示系统错误
                throw new Error('数据库连接失败');
                
            case 'timeout':
                // 演示超时错误
                await new Promise(resolve => setTimeout(resolve, 35000)); // 超过30秒
                break;
                
            default:
                ApiHelper.success(call, { message: '错误处理演示完成' });
        }
    },
    {
        name: 'ErrorHandlingDemo',
        requiredParams: ['action'],
        timeout: 30000
    }
);

// ==================== 使用说明 ====================

/**
 * 使用新架构的步骤：
 * 
 * 1. 在应用启动时初始化服务：
 *    ```typescript
 *    import { quickStart } from '../infrastructure/bootstrap/ServiceBootstrap';
 *    await quickStart();
 *    ```
 * 
 * 2. 定义API处理器：
 *    ```typescript
 *    export const MyApi = ApiFactory.createSimpleHandler(
 *        async (req, context) => {
 *            // 业务逻辑
 *            return result;
 *        },
 *        { name: 'MyApi', requiredParams: ['param1'] }
 *    );
 *    ```
 * 
 * 3. 在TSRPC路由中使用：
 *    ```typescript
 *    // 替换原来的 export default function
 *    export default MyApi;
 *    ```
 * 
 * 4. 享受统一的错误处理、依赖注入和性能监控！
 */
